package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.JedisPool;

import java.util.List;

@Service(interfaceClass = SetmealService.class)
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private SetmealMapper setmealMapper;

    //新增套餐
    @Override
    public void add(Integer[] checkgroupIds, Setmeal setmeal) {
        //新增套餐
        setmealMapper.add(setmeal);
        //中间表
        setSetmealAndCheckGroup(checkgroupIds, setmeal.getId());
        //判断是否上传图片，如果没有图片，将一个null保存到redis会报错。
        if (setmeal.getImg()!=null){
            //将要保存到数据库中的图片保存到redis
            //sadd方法是将数据存入到set集合中的，不允许有重复值
            //用set方法的时候存了一个重复的key，会报错
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        }
    }

    //添加中间表
    private void setSetmealAndCheckGroup(Integer[] checkgroupIds, Integer id) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                setmealMapper.setSetmealAndCheckGroup(checkgroupId, id);
            }
        }
    }

    //分页查询
    @Override
    public PageResult findByPage(Integer currentPage, Integer pageSize, String queryString) {
        //获取第1页，10条内容，默认查询总数count
        PageHelper.startPage(currentPage, pageSize);
        List<Setmeal> list = setmealMapper.findByPage(queryString);
        //用PageInfo对结果进行包装
        PageInfo<Setmeal> setmealPageInfo = new PageInfo<>(list);
        return new PageResult(setmealPageInfo.getTotal(),setmealPageInfo.getList());
    }


    @Override
    public List<Setmeal> findSetmealAll() {
        String list = jedisPool.getResource().get("setmealList");
        if(list==null){
            List<Setmeal> setmealList = setmealMapper.findSetmealAll();
            jedisPool.getResource().set("setmealList",JSON.toJSONString(setmealList));
            return setmealList;
        }else {
            return (List<Setmeal>)JSON.parse(list);
        }
    }
/*11*/
    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setmealMapper.findById(id);
        return setmeal;
    }

/*    //删除
    @Override
    public void deleteById(Integer id) {
        //删除setmeal表
        setmealMapper.deleteById(id);
    }*/


}
